import INotEmptyIdSet from '@/model/form/common/INotEmptyIdSet'
import IResVO from '@/model/vo/common/IResVO'
import { execConfirm, ToastError, ToastSuccess } from '@/util/CommonUtil'
import $http from '@/util/http'
import { AxiosResponse } from 'axios'
import { Dispatch, SetStateAction } from 'react'

// 检查 idSet是否为空
function checkIdSet(idSet: Set<string | number>) {
  if (!idSet || idSet.size === 0) {
    ToastError('请选择数据 (๑´ㅂ`๑)')
    return false
  }
  return true
}

// 统一的删除方法
export default function doDelDataClick(
  url: string,
  selectedList: (string | number)[],
  setSelectedList: Dispatch<SetStateAction<(string | number)[]>>,
  getDataFun: () => void,
  record?: { id: string },
  name?: string,
  msgTip?: string
) {
  const idSet = new Set<string | number>(record ? [record.id] : selectedList)
  const msgTipTemp = msgTip ? msgTip : '删除'
  if (!checkIdSet(idSet)) return
  execConfirm(
    () => {
      return doDelData({ url, idSet, setSelectedList, getDataFun, record })
    },
    undefined,
    name ? `确定${msgTipTemp}【${name}】吗？` : `确定${msgTipTemp}所选项吗？`
  )
}

interface IDoDelData {
  url: string
  idSet: Set<string | number>
  setSelectedList: Dispatch<SetStateAction<(string | number)[]>>
  getDataFun: () => void
  record?: { id: string }
}

// 统一的 删除数据接口
function doDelData({
  url,
  idSet,
  setSelectedList,
  getDataFun,
  record,
}: IDoDelData) {
  return $http
    .post<IResVO, AxiosResponse<IResVO>, INotEmptyIdSet>(url, {
      idSet: [...idSet],
    })
    .then(({ data }) => {
      ToastSuccess(data.msg)
      if (!record) setSelectedList([]) // 重置选中的集合
      getDataFun() // 刷新列表
    })
}
